package servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Appointment;
import entity.Players;
import entity.User;
import session.AppointmentDao;
import session.PlayersDao;
import session.UserDao;

 
/**
 * Kontroler koji omogućuje korisnicima prijavljivanje na termine
 * 
 * @author rigo & jung
 * 
 */
public class AppRegistration extends HttpServlet {
	private static final long serialVersionUID = -5928731605482687316L;
	
	@EJB
	protected UserDao userDao ;
	
	@EJB
	protected AppointmentDao appointmentDao;
	
	@EJB
	protected PlayersDao playersDao;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			User user;
			if((user = (User)request.getSession().getAttribute("user"))==null){
				response.sendRedirect(response.encodeURL("./login.jsp"));
				return;
			}
			Appointment app = new Appointment();
			if( request.getParameter("appId")!=null){
				app = appointmentDao.findById(Integer.parseInt(request.getParameter("appId")));			
			}
			
			if(playersDao.findPlayerByAppointment(user, app)==null){
				Players players = new Players();
				players.setAppointment(app);
				players.setUser(user);
				players.setParticipated(true);
				players.setVote(false);
				players.setGoal(0);
				players.setMvp(0);
				playersDao.merge(players);		
			}else{
				request.setAttribute("message", "Već ste prijavljeni na termin!");
			}
			getServletContext().getRequestDispatcher("/ListAppointments").forward(request, response);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
